<template>
  <div class="home">
    <div class="top" style="display:flex;">
      <div class="left">
        <el-button type="primary" @click="dialogVisible = true;isEdit = false;">新增数据</el-button>
        <el-button type="primary" @click="toExport()">导出数据</el-button>

        <el-upload
          name="XLSX"
          style="margin-left:12px;"
          action="http://localhost:9999/uploadData"
     
       
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel, application/x-xls, application/x-xlw, application/vnd.openxmlformats-officedocument.spreadsheetml.template, application/vnd.ms-excel.sheet.macroEnabled.12, application/vnd.ms-excel.template.macroEnabled.12, application/vnd.ms-excel.addin.macroEnabled.12, application/vnd.ms-excel.sheet.binary.macroEnabled.12"
        >
          <el-button type="primary">上传数据</el-button>
        </el-upload>
        <!-- <el-button type="primary" @click="toUpload()">上传数据</el-button>         -->
      </div>
      <div>
        <el-button type="primary" @click="toDownloadTemplate()">下载模板</el-button>
        <el-input v-model="keyWord" placeholder="请输入要查询的关键字" style="width
    :200px" />
        <el-button type="primary" @click="togetSystemMessages">搜索</el-button>
      </div>
    </div>

    <el-table
      ref="multipleTableRef"
      :data="tableData"
      border
      style="width: 100%"
      :row-key="getRowKeys"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" reserve-selection width="55" />
      <el-table-column type="index" label="序号" width="55" />
      <el-table-column prop="name" label="姓名" width="120" />
      <el-table-column prop="age" label="年龄" width="120" />
      <el-table-column prop="home" label="家乡" w />
      <el-table-column prop="remark" label="备注" />
      <el-table-column fixed="right" label="操作" width="220">
        <template #default="scope">
          <el-button type="danger" size="small" @click="handleClick(scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="toEdit(scope.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      style="margin-top:10px"
      :current-page="pageNum"
      :page-size="pageSize"
      :page-sizes="[10, 20, 30, 40]"
      :background="true"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />

    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑数据' : '新增数据'"
      width="30%"
      @close="resetForm(ruleFormRef)"
    >
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" status-icon>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input v-model="ruleForm.age" />
        </el-form-item>
        <el-form-item label="家乡" prop="home">
          <el-input v-model="ruleForm.home" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="toSubmit(ruleFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  House,
  Message,
  Grid,
  Avatar,
  Position,
  ChatLineSquare,
  Notification,
  Notebook,
  Plus
} from "@element-plus/icons-vue";
import {
  getData,
  addData,
  editData,
  deleteData,
  exportData,
  downloadTemplate
} from "@/api/index";
const isEdit = ref(false);
const dialogVisible = ref(false);
const handleSizeChange = val => {
  pageSize.value = val;
  togetSystemMessages();
};
const handleCurrentChange = val => {
  console.log(`current page: ${val}`);
  pageNum.value = val;
  togetSystemMessages();
};

const tableData = ref([]);
const total = ref(0);

const pageNum = ref(1);
const pageSize = ref(10);
const keyWord = ref();
const togetSystemMessages = () => {
  let data = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    keyWord: keyWord.value
  };
  getData(data).then(res => {
    console.log(res);
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    tableData.value = res.data.data.list;
    total.value = res.data.data.total;
  });
};
const handleClick = row => {
  ElMessageBox.confirm("是否删除?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      let data = {
        id: row.id
      };
      deleteData(data).then(res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        togetSystemMessages();
        ElMessage.success(res.data.message);
      });
    })
    .catch(() => {});
};

const ruleFormRef = ref();
const ruleForm = reactive({
  id: "",
  name: "",
  age: "",
  home: "",
  remark: ""
});

const rules = reactive({
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  age: [{ required: true, message: "请输入年龄", trigger: "blur" }],
  home: [{ required: true, message: "请输入家乡", trigger: "blur" }],
  remark: [{ required: true, message: "请输入备注", trigger: "blur" }]
});

const toSubmit = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (isEdit.value) {
        editData(ruleForm).then(res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          dialogVisible.value = false;
          togetSystemMessages();
          ElMessage.success(res.data.message);
        });
      } else {
        addData(ruleForm).then(res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          dialogVisible.value = false;
          togetSystemMessages();
          ElMessage.success(res.data.message);
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = formEl => {
  if (!formEl) return;
  formEl.resetFields();
};
const toEdit = row => {
  ruleForm.id = row.id;
  ruleForm.name = row.name;
  ruleForm.age = row.age;
  ruleForm.home = row.home;
  ruleForm.remark = row.remark;

  dialogVisible.value = true;
  isEdit.value = true;
};


const getRowKeys =(row) => {
  return row.id
}

const multipleTableRef = ref();
const multipleSelection = ref([]);

const handleSelectionChange = val => {
  multipleSelection.value = val;
};
const toExport = () => {
  if (multipleSelection.value.length <= 0) {
    return ElMessage("选择要导出的数据");
  }
  let data = {
    ids: multipleSelection.value.map(item => item.id).toString()
  };
  exportData(data).then(res => {
    console.log(res);

    const link = document.createElement("a");
    let blob = new Blob([res.data], {
      type:
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"
    });
    link.style.display = "none";
    link.href = URL.createObjectURL(blob);
    link.setAttribute("download", "data.xlsx"); // 文件名可自定义
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
};
const toUpload = () => {};
const toDownloadTemplate = () => {
  downloadTemplate().then(res => {
    const link = document.createElement("a");
    let blob = new Blob([res.data], {
      type:
        "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8"
    });
    link.style.display = "none";
    link.href = URL.createObjectURL(blob);
    link.setAttribute("download", "模板.xlsx"); // 文件名可自定义
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
};

const handleAvatarSuccess = (response, uploadFile) => {
  togetSystemMessages();
  ElMessage.success('上传成功');
};

const beforeAvatarUpload = rawFile => {
  if (rawFile.type !== "Content-Type(Mime-Type)") {
    ElMessage.error("Avatar picture must be JPG format!");
    return false;
  }
  return true;
};
onMounted(() => {
  togetSystemMessages();
});
</script>

<style scoped lang="scss">
.home {
  padding: 20px;
}
.top {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  .left {
    display: flex;
  }
}
</style>